<template>
  <div style="display: inline-table">
    <el-date-picker :class="{'no-icon': noIcon}" :prefix-icon="noIcon?'no-icon':''" :size="size" :disabled="disabled" v-model="date" @change="dateChange" style="display: table-cell" placeholder="日期" :clearable="false"/>
    <el-time-picker :class="{'no-icon': noIcon}" :prefix-icon="noIcon?'no-icon':''" :size="size" :disabled="!date || disabled" @change="timeChange" v-model="time" :format="timeFormat" style="display: table-cell" placeholder="时间" :clearable="clearable"/>
  </div>
</template>
<script>
export default {
  name: 'CDatetimePicker',
  props: {
    noIcon: Boolean,
    disabled: Boolean,
    size: String,
    timeFormat: {
      type: String,
      default () {
        return 'HH:mm:ss'
      }
    },
    valueFormat: String,
    value: {},
    clearable: {
      type: Boolean,
      default () {
        return true
      }
    }
  },
  data () {
    let datetime = null
    if (this.value === '' || this.value === null || this.value === undefined) {
      datetime = null
    } else if (typeof this.value === 'string') {
      datetime = new Date(this.value.replace(/-/g, '/'))
    } else {
      datetime = new Date(this.value)
    }
    return {
      date: datetime,
      time: datetime
    }
  },
  watch: {
    value (v, ov) {
      if (v !== ov) {
        this.date = this.datetime
        this.time = this.datetime
      }
    }
  },
  computed: {
    datetime () {
      if (this.value === '' || this.value === null || this.value === undefined) {
        return null
      } else if (typeof this.value === 'string') {
        return new Date(this.value.replace(/-/g, '/'))
      } else {
        return new Date(this.value)
      }
    }
  },
  methods: {
    dateChange (v) {
      if (v !== null && (this.time === null || this.time === undefined)) {
        this.time = v
      }
      const date = new Date(v.format('yyyy/MM/dd' + ' ' + this.time.format('hh:mm:ss')))
      if (!this.valueFormat) {
        this.$emit('input', date)
      } else {
        this.$emit('input', date.format(this.valueFormat))
      }
    },
    timeChange (v) {
      if (v === null) {
        this.date = null
        this.$emit('input', null)
      } else {
        const date = new Date(this.date.format('yyyy/MM/dd' + ' ' + v.format('hh:mm:ss')))
        if (!this.valueFormat) {
          this.$emit('input', date)
        } else {
          this.$emit('input', date.format(this.valueFormat))
        }
      }
    }
  }
}
</script>

<style>
.no-icon.el-input--prefix .el-input__inner {
  padding: 0 5px;
}
</style>
